﻿using System;
using System.Collections.Generic;
using System.Linq;
using MarriageFertility.Actions;
using MarriageFertility.Mcm;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.ViewModelCollection;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;

namespace MarriageFertility.Helpers;

public static class Helper
{
    public static readonly MBList<TraitObject> RelevantTraits = new MBList<TraitObject>
    {
        DefaultTraits.Honor,
        DefaultTraits.Mercy,
        DefaultTraits.Generosity,
        DefaultTraits.Valor,
        DefaultTraits.Calculating
    };
    
    private static bool IsWeapon(ItemObject item)
    {
        return item.HasWeaponComponent;
    }
    
    public static bool IsWeaponCouch(this ItemObject weapon)
    {
        return IsWeapon(weapon) && CheckWeaponFlag(weapon, flag => flag.Contains("can_couchable"));
    }
    
    private static bool CheckWeaponFlag(ItemObject weapon, Func<string, bool> flagCondition)
    {
        if (weapon == null) return false;
        if (weapon.Weapons == null) return false;
        foreach (var weaponComponentData in weapon.Weapons)
            if (weaponComponentData != null)
            {
                List<(string, TextObject)> flagDetails =
                    CampaignUIHelper.GetFlagDetailsForWeapon(weaponComponentData,
                        MBItem.GetItemUsageSetFlags(weaponComponentData
                            .ItemUsage));
                if (flagDetails != null &&
                    flagDetails.Any(flagDetail =>
                        flagDetail.Item1 != null &&
                        !flagDetail.Item1.IsEmpty() &&
                        flagCondition(flagDetail.Item1)))
                    return true;
            }

        return false;
    }
    
    public static bool HasBadTraits(this Hero hero)
    {
        foreach (var trait in RelevantTraits)
        {
            if (hero.GetTraitLevel(trait) < 0) return true;
        }
        return false;
    }
    
    public static bool IsPlayer(this Hero hero) => hero != null && hero == Hero.MainHero;

    public static bool IsPlayerSpouse(this Hero hero) =>
        hero != null && (Hero.MainHero.Spouse == hero || Hero.MainHero.ExSpouses.Contains(hero));

    public static bool IsPlayerClan(this Hero hero) =>
        hero != null && !hero.IsPlayer() && !hero.IsPlayerSpouse() && hero.Clan == Clan.PlayerClan;

    public static bool IsPlayerClanCompanion(this Hero hero)
    {
        return hero != null && (IsPlayer(hero) || hero.IsPlayerCompanion || hero.Clan == Hero.MainHero?.Clan);
    }

    public static bool CanMarrySpouse(this Hero hero)
    {
        if (MCMSettings.Instance.EnableMoreSpouse) return true;
        return hero != null && (hero.Spouse == null || !hero.Spouse.IsAlive);
    }

    public static Hero HighestRelationSuitor(this Hero hero)
    {
        var potentialSuitors = Hero.AllAliveHeroes.Where(
            h => h.Age >= 18 && h.IsLord && h != Hero.MainHero && !h.IsPrisoner && h.GetRelation(hero) >= 50 &&
                 h.IsFemale != hero.IsFemale && (MCMSettings.Instance.EnableMoreSpouse || h.Spouse == null) && !h.IsSpouse(hero)
        ).ToList();
        if (!potentialSuitors.Any())
        {
            return null;
        }
        var highestRelationSuitor = potentialSuitors.OrderByDescending(h => h.GetRelation(hero)).FirstOrDefault();
        return highestRelationSuitor;
    }

    public static bool GenderSuitable(Hero firstHero, Hero secondHero)
    {
        if (MCMSettings.Instance.EnableSameGender) return true;
        return firstHero.IsFemale != secondHero.IsFemale;
    }
    
    public static void ChangeCompanionOccupation(Hero hero)
    {
        if (hero.CompanionOf == Clan.PlayerClan && hero.IsWanderer)
        {
            try
            {
                RemoveCompanionAction.ApplyByByTurningToLord(Hero.MainHero.Clan, hero);
            }
            catch (Exception)
            {
                
            }

            hero.SetNewOccupation(Occupation.Lord);
        }
    }

    public static void FixPlayerMobileParty()
    {
        // if (MobileParty.MainParty != null)
        // {
        //     if (MobileParty.MainParty.LeaderHero == null)
        //         MobileParty.MainParty.ChangePartyLeader(Hero.MainHero);
        //
        //     var roster = MobileParty.MainParty.MemberRoster;
        //     if (roster != null && !roster.Contains(CharacterObject.PlayerCharacter) && !Hero.MainHero.IsPrisoner)
        //     {
        //         roster.AddToCounts(CharacterObject.PlayerCharacter, 1, true);
        //     }
        //     if (roster != null)
        //     {
        //         int playerCount = roster.GetTroopCount(CharacterObject.PlayerCharacter);
        //         if(playerCount > 1)
        //         {
        //             try
        //             {
        //                 int index = roster.FindIndexOfTroop(CharacterObject.PlayerCharacter);
        //                 roster.SetElementNumber(index, 1);
        //             }
        //             catch (Exception e)
        //             {
        //                 
        //             }
        //         }
        //     }
        // }
    }
}